<?php

include_once ('../utilities.php')

?>
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="../reset.css">
	<link rel="stylesheet" type="text/css" href="../mainStyle.css">
	<link rel="stylesheet" type="text/css" href="../searchButton.css">
	<title>SHPE</title>
</head>
<body>

	<div id="container">
		<?php

$root = '../';
include_once ('../header.php')

?>
        
		<div id="page-body">
            <?php

$editPermissions = false;
$deletePermissions = false;

if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['User']))
{
    // Determine the user's 'edit' and 'delete' permissions.
    $user = unserialize($_SESSION['User']);
    $permissions = $user->getPermissions();
    $query = "SELECT * FROM Permissions WHERE PermissionID = " . $permissions;
    $result = $mysqli->query($query);
    if ($result->num_rows > 0 && ($user->getChapter()->getChapterID() == $_GET["id"] ||
        $_GET["id"] == -1))
    {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        switch ($row['Title'])
        {
            case "President":
            case "Vice-President":
            case "Web-Admin":
                $editPermissions = true;
                $deletePermissions = true;
                break;
        }
    }

    // Check if the project exists (ID > 0). If the ID is -1, a 'create new project page' needs to be shown instead.
    if ($_GET["id"] > 0)
    {

        // Get project data.
        $query = "SELECT * FROM Projects WHERE ProjectID = " . $_GET["id"];
        $result = $mysqli->query($query);

        if ($result->num_rows < 1)
        {
            echo "The project requested does not exist.";
        }
        // Else, show the project.
        else
        {
            $projectRow = $result->fetch_array(MYSQLI_ASSOC);

            // If the users has 'edit' and 'delete' permissions, and the action leading to this page was not a
            // 'delete project submit', the user is either just viewing the project, or is editing the project.
            if (($editPermissions || $deletePermissions) && empty($_POST["delete"]) && empty
                ($_POST["save"]))
            {

?><form name="edit-project" action="./?id=<?=

                $_GET["id"]

?>" method="post"><?php

                if ($editPermissions)
                {
                    // If the user was directed to this page from an 'edit project submit', load the page as 'editable' (a form with fields).
                    if (!empty($_POST["edit"]))
                    {
                        // Display form to edit project.


?>
										<input type="submit" name="save" value="Save Project" class="editButton">
										<input type="submit" name="cancel" value="Cancel" class="editButton">
										<br /><br />
										Name: <input type="text" name="name" value="<?=

                        $projectRow['Name']

?>">
										<br /><br />
										Description:
										<br />
										<textarea type="text" name="description" style="width:600px; height:200px;"><?=

                        $projectRow['Description']

?></textarea>
									<?php

                    }
                    // Else just show the edit button at the top of the page (the 'viewable' version of the data will be loaded later).
                    else
                    {

?>
										<input type="submit" name="edit" value="Edit Project" class="editButton">
									<?php

                    }
                }

                // If the user has 'delete' permissions, show the delete button if not in 'edit mode'.
                if ($deletePermissions)
                {
                    if (empty($_POST["edit"]) && empty($_POST["save"]))
                    {

?>
										<input type="submit" name="delete" value="Delete Project" onclick="return confirm('Are you sure you want to delete this project?');" class="editButton">
									<?php

                    }
                }

?>
							</form>
							<br />
							<?php

            }

            // If sent to this page from a 'delete project' postback, delete the project.
            if (!empty($_POST["delete"]))
            {
                // Delete the project and go back to the chapter page.
                $query = "DELETE FROM Projects WHERE ProjectID = " . $_GET["id"];
                $mysqli->query($query) or die('There was an error deleting the project.' . $mysqli->
                    error);
                echo "The project was deleted successfully!";
            }
            // Otherwise, if not in 'edit mode', check to see if the project was just edited and saved.
            else
                if (empty($_POST["edit"]))
                {
                    // Display project.
                    if (!empty($_POST["save"]))
                    {
                        // The project was just saved. If it's a new project, create it, otherwise update the existing one.
                        if (!empty($_GET["id"]))
                        {
                            // The project exists. Update it.
                            $formattedName = trim($_POST["name"]);
                            if ($formattedName == '')
                                $formattedName = "Untitled Project";
                            $query = sprintf("UPDATE Projects SET Name='%s', Description='%s' WHERE ProjectID = %s",
                                $mysqli->real_escape_string($formattedName), $mysqli->real_escape_string($_POST["description"]),
                                $_GET["id"]);

                            $mysqli->query($query) or die('There was an error updating the project.');

                            if (($editPermissions || $deletePermissions) && empty($_POST["delete"]))
                            {

?>
										<form name="edit-project" action="./?id=<?=

                                $_GET["id"]

?>" method="post">
											<input type="submit" name="edit" value="Edit Project" class="editButton">
											<?php

                                if ($deletePermissions)
                                {
                                    if (empty($_POST["edit"]))
                                    {

?>
														<input type="submit" name="delete" value="Delete Project" onclick="return confirm('Are you sure you want to delete this project?');" class="editButton">
													<?php

                                    }
                                }

?>
										</form>
										<br />
										<?php

                            }
                        }
                    }
                    // Get project data (it might have just been updated from a save above).
                    $query = "SELECT * FROM Projects WHERE ProjectID = " . $_GET["id"];
                    $result = $mysqli->query($query);
                    $projectRow = $result->fetch_array(MYSQLI_ASSOC);

                    $formattedDescription = str_replace(array(
                        "\r\n",
                        "\n",
                        "\r"), '<br />', $projectRow['Description']);

?>
							<h1><?=

                    $projectRow['Name']

?></h1>
							<br />
							<p><?=

                    $formattedDescription

?></p>
						<?php

                }
        }
    }
    // If this else reached, the project ID specified when loading the page is < 0, so a new project is being created.
    else
    {
        // New project being created.
        if (($editPermissions))
        {

?><form name="edit-project" action="./?id=-1" method="post"><?php

            // If 'create' request is empty, display a form to create a project.
            if (empty($_POST["create"]))
            {
                // Set a 'cancel' button that goes back to the chapter page that this 'create project' request was sent from.
                if (!empty($_SESSION['LastViewedChapterID']))
                {

?>
										<input type="submit" name="cancel" value="Cancel" onclick="document.forms['edit-project'].action='<?=

                    $root

?>chapter/?id=<?=

                    $_SESSION['LastViewedChapterID']

?>'" class="editButton">
									<?php

                }

                // Display form to edit project.


?>
                                    <input type="submit" name="create" value="Save Project" class="editButton">
                                    <br /><br />
                                    Name: <input type="text" name="name">
                                    <br /><br />
                                    Description:
                                    <br />
                                    <textarea type="text" name="description" style="width:600px; height:200px;"></textarea>
                                <?php

            }
            // Else, if there is a 'create' request, the form was filled out and this is a postback to submit the new project.
            else
            {
                // An project was created. Insert it into the database, get the new ID, and postback with that ID.
                $formattedName = trim($_POST["name"]);
                if ($formattedName == '')
                    $formattedName = "Untitled Project";
                $query = sprintf("INSERT INTO Projects (Name, Description, ChapterID) VALUES ('%s', '%s', '%s')",
                    $mysqli->real_escape_string($formattedName), $mysqli->real_escape_string($_POST["description"]),
                    $mysqli->real_escape_string($user->getChapter()->getChapterId()));

                $mysqli->query($query) or die('There was an error creating the project.' . $mysqli->
                    error);
                echo "The project was created successfully!";
            }

?>
                        </form>
                        <?php

        }
    }
} else
{

?>
				<p>You must be logged in to view this page.</p>
				<?php

}

?>
		</div>
		
		<?php

include_once ('../footer.php')

?>
	</div>

</body>
</html>